package com.bookstore.back.service.impl;

import com.bookstore.back.entity.User;
import com.bookstore.back.mapper.OrderMapper;
import com.bookstore.back.mapper.UserMapper;
import com.bookstore.back.mapper.UserLogMapper;
import com.bookstore.back.service.AdminService;
import com.bookstore.back.service.UserService;
import com.bookstore.back.service.BookService;
import com.bookstore.back.service.OrderService;
import com.bookstore.back.service.NewsService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 后台管理服务实现类
 *
 * @author 程序猿_Ti
 * @since 2025-07-19
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private NewsService newsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserLogMapper userLogMapper;

    @Autowired
    private UserContextUtil userContextUtil;

    @Override
    public Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 用户统计
        Map<String, Object> userStats = userService.getUserStats();
        stats.put("userCount", userStats.get("totalUsers"));
        stats.put("activeUserCount", userStats.get("activeUsers"));
        
        // 图书统计
        long totalBooks = bookService.count();
        stats.put("bookCount", totalBooks);
        
        // 订单统计
        Map<String, Object> orderStats = orderService.getOrderStats();
        stats.put("orderCount", orderStats.get("totalOrders"));
        stats.put("totalSales", orderStats.get("totalSales"));
        stats.put("pendingOrders", orderStats.get("pendingOrders"));
        stats.put("completedOrders", orderStats.get("completedOrders"));
        
        // 新闻统计
        long totalNews = newsService.count();
        stats.put("newsCount", totalNews);
        
        return stats;
    }

    @Override
    public Map<String, Object> getSalesTrend() {
        Map<String, Object> trendData = new HashMap<>();

        try {
            // 从数据库查询最近12个月的销售趋势数据
            List<Map<String, Object>> salesTrendData = orderMapper.getSalesTrendData();

            // 准备12个月的完整数据
            List<String> months = Arrays.asList(
                "1月", "2月", "3月", "4月", "5月", "6月",
                "7月", "8月", "9月", "10月", "11月", "12月"
            );

            List<Integer> salesData = new ArrayList<>();
            List<Integer> orderData = new ArrayList<>();

            // 如果有真实数据，使用真实数据
            if (!salesTrendData.isEmpty()) {
                // 创建月份到数据的映射
                Map<String, Map<String, Object>> dataMap = new HashMap<>();
                for (Map<String, Object> item : salesTrendData) {
                    String monthName = (String) item.get("month_name");
                    dataMap.put(monthName, item);
                }

                // 按12个月顺序填充数据
                for (String month : months) {
                    Map<String, Object> monthData = dataMap.get(month);
                    if (monthData != null) {
                        // 将BigDecimal转换为Integer
                        Object salesObj = monthData.get("total_sales");
                        Object orderObj = monthData.get("order_count");

                        int sales = salesObj != null ? ((Number) salesObj).intValue() : 0;
                        int orders = orderObj != null ? ((Number) orderObj).intValue() : 0;

                        salesData.add(sales);
                        orderData.add(orders);
                    } else {
                        salesData.add(0);
                        orderData.add(0);
                    }
                }
            } else {
                // 如果没有数据，使用默认值
                for (int i = 0; i < 12; i++) {
                    salesData.add(0);
                    orderData.add(0);
                }
            }

            trendData.put("months", months);
            trendData.put("salesData", salesData);
            trendData.put("orderData", orderData);

        } catch (Exception e) {
            log.error("获取销售趋势数据失败：{}", e.getMessage());
            // 发生异常时返回空数据
            trendData.put("months", Arrays.asList("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"));
            trendData.put("salesData", Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
            trendData.put("orderData", Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
        }

        return trendData;
    }

    @Override
    public List<Map<String, Object>> getCategorySales() {
        List<Map<String, Object>> categoryData = new ArrayList<>();

        try {
            // 从数据库查询分类销售数据
            List<Map<String, Object>> categorySalesData = orderMapper.getCategorySalesData();

            if (!categorySalesData.isEmpty()) {
                // 使用真实数据
                for (Map<String, Object> item : categorySalesData) {
                    Map<String, Object> categoryItem = new HashMap<>();
                    categoryItem.put("name", item.get("category_name"));

                    // 将BigDecimal转换为Integer
                    Object salesObj = item.get("total_sales");
                    int sales = salesObj != null ? ((Number) salesObj).intValue() : 0;
                    categoryItem.put("value", sales);

                    categoryData.add(categoryItem);
                }
            } else {
                // 如果没有数据，返回空列表或默认数据
                log.info("暂无分类销售数据");
            }

        } catch (Exception e) {
            log.error("获取分类销售数据失败：{}", e.getMessage());
            // 发生异常时返回空数据
        }

        return categoryData;
    }

    @Override
    public Map<String, Object> getAdminProfile() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为管理员
            if (!userContextUtil.isCurrentUserAdmin()) {
                throw new RuntimeException("权限不足，只有管理员可以访问");
            }

            User admin = userMapper.selectById(currentUserId);
            if (admin == null) {
                throw new RuntimeException("管理员信息不存在");
            }

            Map<String, Object> profile = new HashMap<>();
            profile.put("id", admin.getId());
            profile.put("username", admin.getUsername());
            profile.put("email", admin.getEmail());
            profile.put("phone", admin.getPhone());
            profile.put("realName", admin.getRealName());
            profile.put("avatar", admin.getAvatar());
            profile.put("gender", admin.getGender());
            profile.put("birthDate", admin.getBirthDate());
            profile.put("createTime", admin.getCreateTime());
            profile.put("updateTime", admin.getUpdateTime());

            return profile;
        } catch (Exception e) {
            log.error("获取管理员个人资料失败：{}", e.getMessage());
            throw new RuntimeException("获取个人资料失败");
        }
    }

    @Override
    public boolean updateAdminProfile(Map<String, Object> profileData) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为管理员
            if (!userContextUtil.isCurrentUserAdmin()) {
                throw new RuntimeException("权限不足，只有管理员可以访问");
            }

            User admin = userMapper.selectById(currentUserId);
            if (admin == null) {
                throw new RuntimeException("管理员信息不存在");
            }

            // 更新个人资料信息
            if (profileData.containsKey("username")) {
                admin.setUsername((String) profileData.get("username"));
            }
            if (profileData.containsKey("email")) {
                admin.setEmail((String) profileData.get("email"));
            }
            if (profileData.containsKey("phone")) {
                admin.setPhone((String) profileData.get("phone"));
            }
            if (profileData.containsKey("realName")) {
                admin.setRealName((String) profileData.get("realName"));
            }
            if (profileData.containsKey("gender")) {
                admin.setGender((Integer) profileData.get("gender"));
            }
            if (profileData.containsKey("birthDate")) {
                String birthDateStr = (String) profileData.get("birthDate");
                if (birthDateStr != null && !birthDateStr.isEmpty()) {
                    admin.setBirthDate(LocalDate.parse(birthDateStr));
                }
            }

            admin.setUpdateTime(LocalDateTime.now());
            int result = userMapper.updateById(admin);
            return result > 0;
        } catch (Exception e) {
            log.error("更新管理员个人资料失败：{}", e.getMessage());
            return false;
        }
    }

    @Override
    public boolean changeAdminPassword(Map<String, String> passwordData) throws RuntimeException {
        // 获取当前登录用户ID
        Long currentUserId = userContextUtil.getCurrentUserId();
        if (currentUserId == null) {
            throw new RuntimeException("未登录或登录已过期");
        }

        // 验证当前用户是否为管理员
        if (!userContextUtil.isCurrentUserAdmin()) {
            throw new RuntimeException("权限不足，只有管理员可以访问");
        }

        String currentPassword = passwordData.get("currentPassword");
        String newPassword = passwordData.get("newPassword");
        String confirmPassword = passwordData.get("confirmPassword");

        if (currentPassword == null || newPassword == null || confirmPassword == null) {
            throw new RuntimeException("密码参数不完整");
        }

        if (!newPassword.equals(confirmPassword)) {
            throw new RuntimeException("新密码与确认密码不一致");
        }

        User admin = userMapper.selectById(currentUserId);
        if (admin == null) {
            throw new RuntimeException("管理员信息不存在");
        }

        // 验证当前密码（明文比较，与登录逻辑保持一致）
        if (!currentPassword.equals(admin.getPassword())) {
            throw new RuntimeException("当前密码错误");
        }

        // 验证新密码不能与当前密码相同
        if (currentPassword.equals(newPassword)) {
            throw new RuntimeException("新密码不能与当前密码相同");
        }

        try {
            // 更新密码（明文存储，与现有数据保持一致）
            admin.setPassword(newPassword);
            admin.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(admin);
            if (result <= 0) {
                throw new RuntimeException("密码更新失败");
            }
            return true;
        } catch (Exception e) {
            log.error("修改管理员密码失败：{}", e.getMessage());
            throw new RuntimeException("密码更新失败：" + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getAdminStats() {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为管理员
            if (!userContextUtil.isCurrentUserAdmin()) {
                throw new RuntimeException("权限不足，只有管理员可以访问");
            }

            Map<String, Object> stats = new HashMap<>();

            // 从用户日志表获取真实的统计数据
            Map<String, Object> userStats = userLogMapper.getUserStats(currentUserId);

            if (userStats != null) {
                // 登录次数
                Object loginCount = userStats.get("loginCount");
                stats.put("loginCount", loginCount != null ? loginCount : 0);

                // 操作次数
                Object operationCount = userStats.get("operationCount");
                stats.put("operationCount", operationCount != null ? operationCount : 0);

                // 最后登录时间
                Object lastLoginTime = userStats.get("lastLoginTime");
                stats.put("lastLoginTime", lastLoginTime != null ? lastLoginTime : "未知");

                // 最后登录IP
                Object lastLoginIp = userStats.get("lastLoginIp");
                stats.put("lastLoginIp", lastLoginIp != null ? lastLoginIp : "未知");
            } else {
                // 如果没有日志记录，返回默认值
                stats.put("loginCount", 0);
                stats.put("operationCount", 0);
                stats.put("lastLoginTime", "未知");
                stats.put("lastLoginIp", "未知");
            }

            // 获取管理员注册时间
            User admin = userMapper.selectById(currentUserId);
            if (admin != null) {
                stats.put("registerTime", admin.getCreateTime());
            }

            return stats;
        } catch (Exception e) {
            log.error("获取管理员统计信息失败：{}", e.getMessage());
            // 返回默认值，避免前端报错
            Map<String, Object> defaultStats = new HashMap<>();
            defaultStats.put("loginCount", 0);
            defaultStats.put("operationCount", 0);
            defaultStats.put("lastLoginTime", "未知");
            defaultStats.put("lastLoginIp", "未知");
            return defaultStats;
        }
    }

    @Override
    public boolean updateAdminAvatar(String avatarUrl) {
        try {
            // 获取当前登录用户ID
            Long currentUserId = userContextUtil.getCurrentUserId();
            if (currentUserId == null) {
                throw new RuntimeException("未登录或登录已过期");
            }

            // 验证当前用户是否为管理员
            if (!userContextUtil.isCurrentUserAdmin()) {
                throw new RuntimeException("权限不足，只有管理员可以访问");
            }

            User admin = userMapper.selectById(currentUserId);
            if (admin == null) {
                throw new RuntimeException("管理员信息不存在");
            }

            admin.setAvatar(avatarUrl);
            admin.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(admin);
            return result > 0;
        } catch (Exception e) {
            log.error("更新管理员头像失败：{}", e.getMessage());
            return false;
        }
    }

}
